/**
 * All Rights Reserved , Copyright (C) 2022 , 青岛鼎信通讯股份有限公司
 * <p>
 * MmsProvinceCityMatchinfoController
 * 省份地市信息表新
 * <p>
 * 修改纪录
 * 2022-01-10 版本：1.0 wangjielei 创建。
 *
 * @version 版本：1.0
 * @author 作者：wangjielei
 * 创建日期：2022-01-10
 */

package com.topscomm.mms.controller;

import java.time.LocalDate;
import java.util.*;

import cn.hutool.http.HttpStatus;
import com.topscomm.mms.MmsSystemConst;
import com.topscomm.mms.pojo.MmsDeptExtraInfoEntity;
import com.topscomm.mms.service.impl.PmsProvinceCityMatchInstanceService;
import com.topscomm.pub.util.*;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.constant.TapHttpErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.topscomm.mms.MmsSystemConst.ItemsEnum;
import com.topscomm.mms.controller.auto.MmsProvinceCityMatchinfoControllerAuto;
import com.topscomm.mms.pojo.MmsProvinceCityMatchinfoEntity;
import com.topscomm.mms.service.impl.MmsDeptExtraInfoService;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.cbo.model.TreeModel;
import com.topscomm.cbo.service.impl.CboItemDetailsService;
import com.topscomm.cbo.service.impl.CboUserRoleService;

import javax.xml.transform.Result;

/**
 * @author: wangjielei
 * @date: 2022-01-10
 * @description:省份地市信息表新Controller
 * @modify:
 */
@RestController
@RequestMapping("mms/provinceCityMatchinfo")
public class MmsProvinceCityMatchinfoController extends MmsProvinceCityMatchinfoControllerAuto implements IMmsProvinceCityMatchinfoController {
    @Autowired
    public MmsDeptExtraInfoService mmsDeptExtraInfoService;
    @Autowired
    public CboUserRoleService cboUserRoleService;
    @Autowired
    public CboItemDetailsService cboItemDetailsService;
    @Autowired
    public PmsProvinceCityMatchInstanceService pmsProvinceCityMatchInstanceService;

    /**
     * @author: hudeyong
     * @date: 2021-06-21
     * @param paraMap
     * @return
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    protected String spellListSql(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" 1 = 1 ");
        // 当选中左树区域时
        if (paraMap.containsKey("qry_id")) {
            String value = paraMap.get("qry_id").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and {0} = '{1}' ", MmsProvinceCityMatchinfoEntity.FieldParentid, value);
            }
            // 进行权限筛选
            this.service.spellSqlByUserLevel(sql, value);
        } else {// 当进行搜索查询时
            if (paraMap.containsKey("qry_name")) {
                String value = paraMap.get("qry_name").toString();
                if (!StringUtil.isEmpty(value)) {
                    sql.appendSingle(" and name like '%{0}%' ", value);
                }
            }
            if (paraMap.containsKey("qry_user")) {
                String value = paraMap.get("qry_user").toString();
                if (!StringUtil.isEmpty(value)) {
                    sql.appendSingle(" and ( areaauthorizationusercode like '%{0}%' or areaauthorizationusername like '%{0}%') ", value);
                }
            }
            if (paraMap.containsKey("qry_arealevel")) {
                String value = paraMap.get("qry_arealevel").toString();
                if (!StringUtil.isEmpty(value)) {
                    sql.appendSingle(" and arealevel = '{0}' ", value);
                }
            }
            if (paraMap.containsKey("qry_name") || paraMap.containsKey("qry_user") || paraMap.containsKey("qry_arealevel")) {
                this.service.spellSqlByUserLevelForQuery(sql);
            }
        }
        return sql.toString();
    }

    /**
     *
     * @description: 参照查询方法
     * @param paraMap
     * @return
     * @author: hudeyong
     * @date: 2021-06-21
     * @modify:
     */
    @Override
    @GetMapping(value = "/refList")
    public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
        return super.refList(paraMap);
    }

    /**
     * @description: // 查询部门code
     * @param: [paraMap]
     * @return:
     * @author: wanghjielei
     * @date: 2022/1/11 20:45
     * @modify:
     */
    @GetMapping(value = "/queryDeptcommoncode")
    public ResponseResult<Object> queryDeptcommoncode(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            StringBufferProxy sql = new StringBufferProxy();
            String usercode = this.getUserBean().getUser().getCode();
            sql.appendSingle(" {0} = '{2}' or {1} = '{2}' ", MmsDeptExtraInfoEntity.FieldProvincemanagercode,
                    MmsDeptExtraInfoEntity.FieldCfocode, usercode);
            MmsDeptExtraInfoEntity mmsDeptExtraInfoEntity = mmsDeptExtraInfoService.queryObjectByWhere(sql.toString());
            Map<String, Object> resultMap = new HashMap<>();
            String deptCommonCode = "";
            if (mmsDeptExtraInfoEntity == null) {
                deptCommonCode = mmsDeptExtraInfoService.getDeptCommonCode(this.getUserBean().getDept().getCode());
            } else {
                deptCommonCode = mmsDeptExtraInfoEntity.getDeptcommoncode();
            }
            resultMap.put("deptcommoncode", deptCommonCode);
            return ResponseResult.ok(resultMap);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: // 查询当前用户等级
     * @param: [paraMap]
     * @return:
     * @author: wanghjielei
     * @date: 2022/1/12 9:26
     * @modify:
     */
    @GetMapping(value = "/queryLevel")
    public ResponseResult<Object> queryLevel(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            String userCode = getUserBean().getUser().getCode();
            String userLevel = this.service.queryLevel(userCode);
            Map<String, Object> map = new HashMap<>();
            map.put("userLevel", userLevel);
            return ResponseResult.ok(map);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: 根据工号返回用户所有有权限的区域（可添加筛选条件：创建部门编号）
     * @param paraMap
     * @throws ServiceException
     * @author: hudeyong
     * @date: 2021-6-24 16:36:21
     * @modify:
     */
    @GetMapping(value = "/acquireAllLowerArea")
    public ResponseResult<Object> acquireAllLowerArea(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            List<Map<String, Object>> resultMap = this.service.acquireAllLowerArea(paraMap);
            return ResponseResult.ok(resultMap);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: 根据工号找到这个人的所有上级区域（可添加筛选条件：创建部门编号）
     * @param paraMap
     * @throws ServiceException
     * @author: hudeyong
     * @date: 2021-7-08
     * @modify:
     */
    @GetMapping(value = "/acquireAllUpArea")
    public ResponseResult<Object> acquireAllUpArea(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            List<MmsProvinceCityMatchinfoEntity> resultMap = this.service.acquireAllUpArea(paraMap);
            return ResponseResult.ok(resultMap);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     *
     * @description: 一级部门树查询方法
     * @param paraMap
     * @return
     * @author: hudeyong
     * @date: 2021-06-21
     * @modify:
     */
    @GetMapping(value = "/queryTreeList")
    public ResponseResult<Object> queryTreeList(@RequestParam(required = false) Map<String, Object> paraMap) {
        String userCode = getUserBean().getUser().getCode();
        List<TreeModel> treeList = this.service.queryTreeList(userCode);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("dataList", treeList);
        return ResponseResult.ok(dataMap);
    }


    /**
     * @description: // 检查当前用户是否省级负责人
     * @param: []
     * @return:
     * @author: wanghjielei
     * @date: 2022/1/10 16:30
     * @modify:
     */
    public Boolean checkIsProvinces() {
        boolean key = false;
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("usercode", getUserBean().getUser().getCode());
        int count = this.service.getCount(paraMap, "getProvincesCount");
        if (count > 0) {
            return true;
        }
        return key;
    }

    /**
     *
     * @description: 上级区域树查询方法
     * @param paraMap
     * @return
     * @author: hudeyong
     * @date: 2021-06-21
     * @modify:
     */
    @GetMapping(value = "/queryParentTreeList")
    public ResponseResult<Object> queryParentTreeList(@RequestParam(required = false) Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        Map<String, Object> paramMap = new HashMap<>();
        sql.appendSingle(" 1=1 ");
        if (paraMap.containsKey("qry_code")) {
            String value = paraMap.get("qry_code").toString();
            paramMap.put("code", value);
        }
        List<Map<String, Object>> listModule = this.service.queryMap(paramMap, "queryParentAll");
        List<Map<String, Object>> listNewModule = new ArrayList<Map<String, Object>>();
        listNewModule.addAll(listModule);
        TreeModel treeModel = new TreeModel();
        List<TreeModel> treeList = treeModel.buildTree(listNewModule, false, "");
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("dataList", treeList);
        return ResponseResult.ok(dataMap);
    }

    @Override
    @PutMapping(value = "/submit")
    public ResponseResult<Object> submit(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            Map<String, Object> dataMap = paraMap;
            dataMap.put("submitdate", new Date());
            beforeSubmit(dataMap, paraMap);
            String mailTitle = "";
            if (dataMap.containsKey("maintitle")) {
                mailTitle = ConvertUtil.convertToString(dataMap.get("maintitle"));
            }
            TapEntity entity = this.service.queryById(ConvertUtil.convertToString(dataMap.get("id")));
            if (entity == null) {
                //Class<T> entityClass = this.entityClass;
                //entity = entityClass.newInstance();
                entity = new MmsProvinceCityMatchinfoEntity();
            }
            // 处于审批中和已审批的单据不能再提交审批
            for (Object key : dataMap.keySet()) {
                String tempKey = ConvertUtil.convertToString(key);
                entity.setValue(tempKey, dataMap.get(key));
            }
            this.service.executeSubmit(entity, mailTitle, this.getUserBean());
            dataMap = this.service.queryMapById(ConvertUtil.convertToString(dataMap.get("id")));
            // 增加前台待审批消息提醒
            afterSubmit(dataMap, paraMap);
            return ResponseResult.ok("提交成功");
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     *
     * @description: 提交审批前
     * @param dataMap
     * @param paraMap
     * @throws Exception
     * @author: wangjielei
     * @date: 2022-01-10
     * @modify:
     */
    @Override
    protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
        super.beforeSubmit(dataMap, paraMap);
        StringBufferProxy mailtitle = new StringBufferProxy();
        mailtitle.appendSingle("{0}{1}于{2}提交省份地市信息表新申请,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"), DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
        dataMap.put("maintitle", mailtitle.toString());
    }

    /**
     *
     * @description: 查询是否为省总或CFO
     * @throws Exception
     * @author: zhangjunyao
     * @date: 2022-01-21
     * @modify:
     */
    @GetMapping(value = "/whetherCfoOrPm")
    public ResponseResult<Object> whetherCfoOrPm() {
        try {
            Boolean isCfoOrPm = this.service.checkIsTop();
            return ResponseResult.ok(isCfoOrPm);
        } catch (Exception ex) {
            return this.handleControllerException(ex);
        }
    }

    /**
     *
     * @description: 查询是否为市级负责人
     * @throws Exception
     * @author: zhangjunyao
     * @date: 2022-01-21
     * @modify:
     */
    @GetMapping(value = "/queryCity")
    public ResponseResult<Object> queryCity() {
        try {
            Boolean isCity = this.service.checkIsCitys();
            List<String> cityNameList = null;
            if (isCity) {
                cityNameList = this.service.queryCity();
            }
            return ResponseResult.ok(cityNameList);
        } catch (Exception ex) {
            return this.handleControllerException(ex);
        }
    }

    /**
     *
     * @description: 查询一级部门（仅省总/CFO时需要）
     * @throws Exception
     * @author: zhangjunyao
     * @date: 2022-01-21
     * @modify:
     */
    @GetMapping(value = "/queryDeptCommonCode")
    public ResponseResult<Object> queryDeptCommonCode() {
        try {
            String deptCommonCode = mmsDeptExtraInfoService.getDeptCommonCode(getUserBean().getDept().getCode());
            String deptCommonName = datacodeCache.getValueDynamic("DeptCommonCodeTrack", deptCommonCode, "code", "name");
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("deptCommonCode", deptCommonCode);
            resultMap.put("deptCommonName", deptCommonName);
            return ResponseResult.ok(resultMap);
        } catch (Exception ex) {
            return this.handleControllerException(ex);
        }
    }

    /**
     *
     * @description: 重写删除接口实现级联删除
     * @param paraMap
     * @author: zhangjunyao
     * @date: 2022-02-15
     * @modify:
     */
    @Override
    @DeleteMapping({"/delete"})
    public ResponseResult<Object> delete(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            String ids = ConvertUtil.convertToString(paraMap.get("ids"));
            this.service.deleteCascade(ids);
            this.afterDelete(paraMap);
            return ResponseResult.ok("删除成功");
        } catch (Exception ex) {
            return this.handleControllerException(ex);
        }
    }

    /**
     * @description: 禁用、启用区域
     * @author xinfushuo
     * @param paraMap
     * id
     * pmsenableddate
     * @date 2022/3/25
     */
    @GetMapping(value = "/flipUseful")
    public ResponseResult<Object> flipUseful(@RequestParam Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            //若存在未禁用子级区域 则禁止禁用该区域
            Map<String, Object> updateMap = this.service.queryMap(paraMap, "queryByIDForHasChild").get(0);
            if (ConvertUtil.convertToString(updateMap.get("haschild")).contentEquals("1") && ConvertUtil.convertToString(updateMap.get(MmsProvinceCityMatchinfoEntity.FieldUseful)).contentEquals("1")) {
                return ResponseResult.error(HttpStatus.HTTP_OK, "存在下级区域，不允许禁用");
            }
            updateMap.put(MmsProvinceCityMatchinfoEntity.FieldUseful, MmsSystemConst.ProvinceCityUseful.flipUseful(ConvertUtil.convertToString(updateMap.get(MmsProvinceCityMatchinfoEntity.FieldUseful))));
            updateMap.put(MmsProvinceCityMatchinfoEntity.FieldPmsenableddate, paraMap.get(MmsProvinceCityMatchinfoEntity.FieldPmsenableddate));
            this.service.update(updateMap);
            MmsProvinceCityMatchinfoEntity entity = this.service.queryById(ConvertUtil.convertToString(paraMap.get("id")));
            if(ConvertUtil.convertToString(updateMap.get(MmsProvinceCityMatchinfoEntity.FieldUseful)).contentEquals("0")){
                pmsProvinceCityMatchInstanceService.syncDisabled(entity);
            }else{
                this.service.generateInstance(entity);
            }
            return ResponseResult.ok(updateMap);
        } catch (Exception e) {
            return this.handleControllerException(e);
        }
    }
}
